package com.xxxx.server.config.security;

import com.xxxx.server.config.security.compoent.*;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private IAdminService adminService;
    @Autowired
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private CustomFilter customFilter;
    @Autowired
    private CustomUrlDecisionManager customUrlDecisionManager;

    /**
     * ctrl+o 选择configure()，因为UserDetailsService是已经重写之后的，
     * 让spring security走登录逻辑的时候，走我们自己去实现的UserDetailsService
     * 入参是web security
     * passwordEncoder也要注入，用的是BCryptPasswordEncoder()类
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }
    // 放行路径，不走拦截链接
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 放行静态资源
        web.ignoring().antMatchers(
                "/login",
                "/logout",
                "/css/**",
                "/js/**",
                "/index.html",
                "/img/**",
                "/fonts/**",
                "/favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/captcha");
    }

    // spring security的完整配置，使用jwt（需要准备相关过滤器），不需要csrf，基于token，不需要session
    // 入参是HTTP security
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 使用Jwt，不需要csrf
        http.cors()
                .disable()
                // 基于token，不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 所有请求都要认证
                .anyRequest()
                .authenticated()
                // 动态权限配置
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(customUrlDecisionManager);
                        object.setSecurityMetadataSource(customFilter);
                        return object;
                    }
                })
                .and()
                // 禁用缓存
                .headers()
                .cacheControl();
        // 添加 jwt 登录 授权过滤器
        http.addFilterBefore(jwtAuthencationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        // 添加自定义未授权和未登录的结果返回(写在RestAuthorizationEntryPoint和RestfulAccessDeniedHandler类中)
        http.exceptionHandling()
                // 未授权
                .accessDeniedHandler(restfulAccessDeniedHandler)
                // 未登录
                .authenticationEntryPoint(restAuthorizationEntryPoint);
    }

    /**
     * 008配置Security登录授权过滤器
     * UserDetailsService 是 WebSecurityConfigurerAdapter 中存在
     * UserDetailsService 是 security.core.userdetails中的一个接口
     */
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        // 使用getAdminByUserName去实现
        return username -> {
            Admin admin = adminService.getAdminByUserName(username);
            // 判断，如果admin不为空，就设置角色信息和返回admin
            if (null != admin) {
                admin.setRoles(adminService.getRoles(admin.getId()));
                return admin;
            }
            // 使用springSecurity提供的异常
            throw new UsernameNotFoundException("用户名密码不正确");
        };
    }

    /**
     * passwordEncoder 是 security.crypto的一个接口，用于实现密码匹配
     * PasswordEncoder 在 security中用的具体的实现是BCryptPasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //AnnotationConfigApplicationContext将配置类中标注了@Bean的方法的返回值识别为Spring Bean，并注册到容器中，归入IoC容器管理。
    @Bean
    public JwtAuthencationTokenFilter jwtAuthencationTokenFilter() {
        return new JwtAuthencationTokenFilter();
    }

}
